/* 
 * 	This file is part of VPN Monitor Project 7..

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package monitor.utility;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * Generic class for saving and reading object, intended
 * use is for serialization and deserialization.
 *
 * @param <C> Object type that should be stored or read.
 */
public class SerializationIO<C> {
	
	/**
	 * Reading an object from a file, do an unchecked cast to
	 * the class C.
	 * @param name File name from which the object should be read.
	 * @return The object.
	 * @throws FileNotFoundException - if the file of the file name don't exist.
	 * @throws ClassNotFoundException
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	public C readClassObject (String name) throws FileNotFoundException, ClassNotFoundException, IOException{
		File file = new File(name);
		if (!file.exists())
			throw new FileNotFoundException();
		ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
		return (C) ois.readObject();
	}
	
	/**
	 * Storing a specific object to file with specified file name, also
	 * if the method should overwrite the file if it already exist.
	 * @param object Object that should be stored.
	 * @param fileName Desired file name.
	 * @param overWrite If an existing file should be overwritten.
	 * @throws IOException
	 */
	public void writeClassObject(C object, String fileName, boolean overWrite) throws IOException{
		File file = new File(fileName);
		if(file.exists() && !overWrite)
			throw new IOException("File "+fileName+" exist, can't overWrite.");
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
		oos.writeObject(object);
	}
}
